package com.yys.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.yys.common.utils.R;
import com.yys.gulimall.ware.feign.MemberFeignService;
import com.yys.gulimall.ware.vo.FareVo;
import com.yys.gulimall.ware.vo.MemberAddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yys.common.utils.PageUtils;
import com.yys.common.utils.Query;

import com.yys.gulimall.ware.dao.WareInfoDao;
import com.yys.gulimall.ware.entity.WareInfoEntity;
import com.yys.gulimall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");

        if(!StringUtils.isEmpty(key)) {
            wrapper.and(w ->
                w.eq("id",key)
                        .or().like("name",key)
                        .or().like("areacode",key)
                        .or().like("address",key)
            );
        }

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public FareVo getFare(Long addrId) {
        FareVo fareVo = new FareVo();
        R r = memberFeignService.info(addrId);
        MemberAddressVo data = r.getData("memberReceiveAddress",new TypeReference<MemberAddressVo>() {});
        if(ObjectUtils.isNotNull(data)) {
            //TODO 我们不再做复杂处理了,我们直接指定运费为手机号的最后一位
            String phone = data.getPhone();
            BigDecimal fare = new BigDecimal(phone.substring(phone.length() - 1));
            fareVo.setFare(fare);
        }
        fareVo.setAddress(data);
        return fareVo;
    }

}